package nguyen.huu.phong.slidetext;

import java.awt.Color;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.swing.JOptionPane;

public class Configure implements Serializable{
	private static final long serialVersionUID = 96678343791424943L;
	private transient static Configure configure;
	public String title = "Slide Text v1.0";
	public String defaultFolder = ".";
	public int width = Toolkit.getDefaultToolkit().getScreenSize().width;
	public int height = 40;
	public Point location = new Point(0, Toolkit.getDefaultToolkit().getScreenSize().height - height - 40);
	public long sleepTime = 10000;
	public Color color = Color.BLUE;
	public float fontSize = 20.0f;
	
	public static Configure getInstance(){
		if (configure == null) configure = load();
		return configure;
	}
	
	private Configure(){
	}
	
	public void save(){
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Slide Text.conf"));
			out.writeObject(this);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static Configure load(){
		Configure that = new Configure();
		File file = new File("Slide Text.conf");
		if (!file.exists()) return that;
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
			Object object = in.readObject();
			if (object instanceof Configure){
				Configure exist = (Configure) object;
				if (exist.title != null && exist.title.equals(that.title)){
					that = exist;
				}else{
					JOptionPane.showMessageDialog(null, "File old configure of " + exist.title +  " is not compatible with " + that.title + "\r\nOld configure will rename to " + exist.title + ".old.conf", "Loading configuare", JOptionPane.INFORMATION_MESSAGE);
					boolean rename = false;
					try {
						ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(exist.title + ".old.conf"));
						out.writeObject(exist);
						out.flush();
						out.close();
						rename = true;
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					JOptionPane.showMessageDialog(null, "Rename is " + (rename ? "Successfull" : "Fail") + "\r\nOld configuare will replace with default configuare of " + that.title, "Loading configuare", JOptionPane.INFORMATION_MESSAGE);
				}
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return that;
	}
}
